<?php 
namespace Futures\Controller;
use Common\Api\SendSMSApi;
//use Think\Controller;
//use Common\Api\WxPayApi;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class PayController extends BaseController {
	// 猜涨跌首页
	
	/**
	 * [personal_incharge 金额充值页面]
	 * @return [type] [description]
	 */
	public function personal_incharge(){
		$user_auth= cookie('user_auth');
		$user_info = M('Follow')->field('nickname,money')->where(array('openid'=>$user_auth['openid']))->find();
		//$user_money = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('money');
		$this->assign('nickname',$user_info['nickname']);
		$this->assign('user_money',$user_info['money']);
		$this->display();
	}
	
	public function incharge_insure(){
		
		$money = I('post.money');
		if($money<0.03){
			$this->error('充值最低金额为50元！');
		}
		//import('Futures.ZfPay.wechatPay');
		//import('Futures.ZfPay.phpqrcode');
		//import('Futures.ZfPay.merchant');
		include ('phpqrcode.php');
		require_once('merchant.php');
		//vendor ('ZfPay.phpqrcode');
		//vendor('ZfPay.merchant');

		$data = array();
		$user_auth= cookie('user_auth');
		$data['user_id'] = $user_auth['uid'];
		$data['openid'] = $user_auth['openid'];
		if($data['openid']!='okLy4wfSMkYwRsQ5pULwfvmd5n58'){
			//$this->error('系统更新中');
		}
		$data['money'] = $money;
		$data['create_time'] = time();
		$data['is_pay'] = 0;
		$data['pay_type'] = 1;
		$data['bank_id'] = 0;
		//商户单号
		$merchant_code = "2020600826";
		$out_trade_no = 'hjw'.$data['user_id'].$merchant_code.date("YmdHis").mt_rand(1000,9999);
		$data['out_trade_no'] = $out_trade_no;
		$res = M('FuturesRecharge')->add($data);
		if(!$res){
			$this->error('充值出错！');
		}
		$openId= $user_auth['openid'];

		$priKey= openssl_get_privatekey($priKey);
		//echo "Key:".$priKey,'<hr>';
		
		$service_type = "wxpay";
		//$notify_url = "http://www.dinpay.com/Notify_Url.jsp";
		//$notify_url = "http://qtest.fivip.com/futures.php/Pay/zfnotify";	
		$notify_url = U('Pay/zfnotify');		
		$interface_version ="V3.0"; 
		$sign_type = "RSA-S";
		//$order_no = "10002016665";
		$order_no = $out_trade_no;
		$this->assign('order_no',$order_no);
		$this->assign('money',$money);
		//session($order_no,0);	
		//$order_time = "2015-11-11 12:12:12";
		$order_time = date('Y-m-d H:i:s');	
		//$order_amount ="0.01" ;	
		$order_amount = $money;
		$product_name = "充值";	
		$product_code = "";	
		$product_num = "";
		$product_desc = "";	
		$extra_return_param = "";	
		$extend_param = "";
		$signStr = "";
		if($extend_param != ""){
			$signStr = $signStr."extend_param=".$extend_param."&";
		}
		if($extra_return_param != ""){
			$signStr = $signStr."extra_return_param=".$extra_return_param."&";
		}	
		$signStr = $signStr."interface_version=".$interface_version."&";		
		$signStr = $signStr."merchant_code=".$merchant_code."&";		
		$signStr = $signStr."notify_url=".$notify_url."&";			
		$signStr = $signStr."order_amount=".$order_amount."&";			
		$signStr = $signStr."order_no=".$order_no."&";			
		$signStr = $signStr."order_time=".$order_time."&";	
		if($product_code != ""){
			$signStr = $signStr."product_code=".$product_code."&";
		}		
		if($product_desc != ""){
			$signStr = $signStr."product_desc=".$product_desc."&";
		}
		$signStr = $signStr."product_name=".$product_name."&";

		if($product_num != ""){
			$signStr = $signStr."product_num=".$product_num."&";
		}	
		$signStr = $signStr."service_type=".$service_type;	
		openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
		$sign = urlencode(base64_encode($sign_info));			
		$postdata = "";
		if($extend_param != ""){
			$postdata = $postdata.'extend_param='.$extend_param."&";
		}
		if($extra_return_param != ""){
			$postdata = $postdata.'extra_return_param='.$extra_return_param."&";
		}
		if($product_code != ""){
			$postdata = $postdata.'product_code='.$product_code."&";
		}	
		if($product_desc != ""){
			$postdata = $postdata.'product_desc='.$product_desc."&";
		}	
		if($product_num != ""){
			$postdata = $postdata.'product_num='.$product_num."&";
		}	
		$postdata = $postdata.'merchant_code='.$merchant_code."&";
		$postdata = $postdata.'service_type='.$service_type."&";
		$postdata = $postdata.'notify_url='.$notify_url."&";
		$postdata = $postdata.'interface_version='.$interface_version."&";
		$postdata = $postdata. 'sign_type='.$sign_type."&";
		$postdata = $postdata.'sign='.$sign."&";
		$postdata = $postdata.'order_no='.$order_no."&";
		$postdata = $postdata.'order_time='.$order_time."&";
		$postdata = $postdata.'order_amount='.$order_amount."&";
		$postdata = $postdata.'product_name='.$product_name;
		//echo "发送到智付的数据为："."<br>".$postdata."<br>";
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,"https://api.dinpay.com/gateway/api/weixin");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_POST, true);
	    curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);  
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$response=curl_exec($ch);
		$res=simplexml_load_string($response);
		//var_dump($res);
		$resp_code=$res->response->resp_code;			
		if($resp_code=="SUCCESS"){
			$qrcode=$res->response->trade->qrcode;
			//var_dump($qrcode);
			$pic1="./Public/zfpay/{$out_trade_no}-qrcode.png";
			$pic2="./Public/zfpay/{$out_trade_no}-output.png";
			$errorCorrectionLevel = 'L';
			$matrixPointSize = 10;
			if(file_exists($pic1) or file_exists($pic2)){								
				unlink($pic1);
				unlink($pic2);
			}
			\QRcode::png ( $qrcode, $pic1, $errorCorrectionLevel, $matrixPointSize, 2 );
			$QR = $pic1;
			$logo = './logo.png';
			if ($logo !== FALSE) {
				$QR = imagecreatefromstring ( file_get_contents ( $QR ) );
				$logo = imagecreatefromstring ( file_get_contents ( $logo ) );
				$QR_width = imagesx ( $QR );
				$QR_height = imagesy ( $QR );
				$logo_width = imagesx ( $logo );
				$logo_height = imagesy ( $logo );
				$logo_qr_width = $QR_width / 7;
				$scale = $logo_width / $logo_qr_width;
				$logo_qr_height = $logo_height / $scale;
				$from_width = ($QR_width - $logo_qr_width) / 2;
				imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );
			}
			imagepng ( $QR, $pic2 );
			imagedestroy($QR);
			$this->assign('qr',$pic2);
			$this->display('pay');
			//echo "扫描二维码支付：" ."<br>"."<img src='{$pic2}'>";
		}
		curl_close($ch);
	}

	public function zfnotify(){
		//import('Futures.ZfPay.wechatPay');
		require_once('merchant.php');
		$pubKey = openssl_get_publickey($pubKey);
		$merchant_code	= $_POST["merchant_code"];	
		$notify_type = $_POST["notify_type"];
		$notify_id = $_POST["notify_id"];
		$interface_version = $_POST["interface_version"];
		$sign_type = $_POST["sign_type"];
		$dinpaySign = base64_decode($_POST["sign"]);
		$order_no = $_POST["order_no"];
		$order_time = $_POST["order_time"];	
		$order_amount = $_POST["order_amount"];
		$extra_return_param = $_POST["extra_return_param"];
		$trade_no = $_POST["trade_no"];
		$trade_time = $_POST["trade_time"];
		$trade_status = $_POST["trade_status"];
		$bank_seq_no = $_POST["bank_seq_no"];
		$signStr = "";
		if($bank_seq_no != ""){
			$signStr = $signStr."bank_seq_no=".$bank_seq_no."&";
		}

		if($extra_return_param != ""){
			$signStr = $signStr."extra_return_param=".$extra_return_param."&";
		}	
		$signStr = $signStr."interface_version=".$interface_version."&";	
		$signStr = $signStr."merchant_code=".$merchant_code."&";
		$signStr = $signStr."notify_id=".$notify_id."&";
		$signStr = $signStr."notify_type=".$notify_type."&";
	    $signStr = $signStr."order_amount=".$order_amount."&";	
	    $signStr = $signStr."order_no=".$order_no."&";	
	    $signStr = $signStr."order_time=".$order_time."&";	
	    $signStr = $signStr."trade_no=".$trade_no."&";	
		$signStr = $signStr."trade_status=".$trade_status."&";	
		$signStr = $signStr."trade_time=".$trade_time;		 
		if(openssl_verify($signStr,$dinpaySign,$pubKey,OPENSSL_ALGO_MD5)){			
		
			$out_trade_no = $order_no;
			$set = array();
			$set['transaction_id'] = $notify_id;
			$set['is_pay'] = 1;
			$set['pay_time'] = $trade_time;
			$where = array();
			//$where['openid'] = $data['openid'];
			$where['out_trade_no'] = $out_trade_no;
			$where['is_pay'] = 0;
			$res = M('FuturesRecharge')->where($where)->save($set);
			if(!$res){
				return false;
			}
			$money = $order_amount/100;
			$openid = M('FuturesRecharge')->where(array('out_trade_no'=>$out_trade_no))->getField('openid');
			modify_account($openid,$order_amount,1,'充值');
			session($out_trade_no,1);
			echo "SUCCESS";	
			//header("location:http://qtest.fivip.com/futures.php?s=/Payments/payments.html");
			exit;
			//header("location:http://".$_SERVER['HTTP_HOST'].'/futures?s=/Payments/payments.html');
			//$this->redirect('Pay/success_incharge', array('money' => $order_amount));
		}else{
			echo "Signature verification failed";  
			//$this->redirect('Pay/err_incharge');
		}
	}

	public function toajax(){
		$order_no = I('post.order_no');
		$is_pay = M('FuturesRecharge')->where(array('out_trade_no'=>$order_no))->getField('is_pay');
		//$flag = session($order_no);
		$sucurl = U('Pay/success_incharge',array('money'=>$money));
		$datas['f']=$is_pay;
		$datas['sucurl'] = $sucurl;
		$this->ajaxReturn($datas,'JSON');
	}

	
	public function incharge_insureold(){
		$money = I('post.money');
		if($money<10){
			$this->error('请填入正确的金额！');
		}
		import('Futures.WxPay.lib.WxPayApi');
		$data = array();
		$user_auth= cookie('user_auth');
		$data['user_id'] = $user_auth['uid'];
		$data['openid'] = $user_auth['openid'];
		$data['money'] = $money;
		$data['create_time'] = time();
		$data['is_pay'] = 0;
		$data['pay_type'] = 1;
		$data['bank_id'] = 0;
		//商户单号
		$out_trade_no = \WxPayConfig::MCHID.date("YmdHis").mt_rand(1000,9999);
		$data['out_trade_no'] = $out_trade_no;
		$res = M('FuturesRecharge')->add($data);
		if(!$res){
			$this->error('充值出错！');
		}
		$openId= $user_auth['openid'];
		
		//$openId='o6VUpxI3SRM2vaw9FJIMUmxjO2to';
		//dump($openId);exit;
		//import('Futures.WxPay.lib.WxPayApi');
		//import('Futures.WxPay.WxPayData.php');
		
		//exit;
		//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody("充值");
		$input->SetAttach("虚拟商品");
		//$input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
		$input->SetOut_trade_no($out_trade_no);
		$input->SetTotal_fee($money*100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("期权交易");
		$input->SetNotify_url("http://hjw.fivip.com/futures.php/Pay/notify");
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId);
		$order = \WxPayApi::unifiedOrder($input);
		//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
		if(!empty($openId)) $jsApiParameters = $this->GetJsApiParameters($order);
		//dump($jsApiParameters);
		$sucurl = U('Pay/success_incharge',array('money'=>$money));
		$errurl = U('Pay/err_incharge');
		//echo $returnurl;
		$this->assign('money',$money);
		$this->assign('sucurl',$sucurl);
		$this->assign('errurl',$errurl);
		$this->assign('jsApiParameters',$jsApiParameters);
        $this->display();

	}

	public function GetJsApiParameters($UnifiedOrderResult)
	{
		if(!array_key_exists("appid", $UnifiedOrderResult)
		|| !array_key_exists("prepay_id", $UnifiedOrderResult)
		|| $UnifiedOrderResult['prepay_id'] == "")
		{
			throw new \WxPayException("参数错误");
		}
		$jsapi = new \WxPayJsApiPay();
		$jsapi->SetAppid($UnifiedOrderResult["appid"]);
		$timeStamp = time();
		$jsapi->SetTimeStamp("$timeStamp");
		$jsapi->SetNonceStr(\WxPayApi::getNonceStr());
		$jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
		$jsapi->SetSignType("MD5");
		$jsapi->SetPaySign($jsapi->MakeSign());
		$parameters = json_encode($jsapi->GetValues());
		return $parameters;
	}

	public function notify(){
		import('Futures.WxPay.lib.WxPayApi');
		import('Futures.WxPay.lib.WxPayNotify');
		$notify = new \WxPayNotify();
		$notify->Handle(true);
	}

	public function success_incharge(){
		$money = I('get.money');
		//AccessToken
		$access_token = $this->getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
		$user_auth= cookie('user_auth');
		//modify_account($user_auth['openid'],100,1,'充值');
		$w_url = U('Pay/personal_incharge');
		$picurl = '';
		$post_msg = '{
       		"touser":"'.$user_auth['openid'].'",
       		"msgtype":"news",
       		"news":{
           		"articles": [
            	{
                	"title":"充值成功",
                	"description":"充值'.$money.'成功！",
                	"url":"'.$w_url.'",
                	"picurl":"'.$picurl.'"
            	}
            	]
       		}
   		}';
		$ret_json = $this->curl_grab_page($url, $post_msg);
		$ret = json_decode($ret_json);
		
		if($ret->errmsg != 'ok') {
			$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
			$ret_json = $this->curl_grab_page($url, $post_msg);
			$ret = json_decode($ret_json);
		}
		$sendsms=new SendSMSApi();
		$nickname = $user_auth['nickname'];
		$mobile='18980439909';
		$content = '客户'.$nickname.'在'.date('Y-m-d H:i:s').'充值'.$money.'元。';
        //$res = $sendsms->sendqSMS($mobile,$content);
		$this->display();
	}

	public function err_incharge(){
		$this->display();
	}

	function curl_grab_page($url,$data,$proxy='',$proxystatus='',$ref_url=''){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	if ($proxystatus == 'true')
	{
		curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
		curl_setopt($ch, CURLOPT_PROXY, $proxy);
	}
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_URL, $url);
	if(!empty($ref_url))
	{
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
		curl_setopt($ch, CURLOPT_REFERER, $ref_url);
	}
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	ob_start();
	return curl_exec ($ch);
	ob_end_clean();
	curl_close ($ch);
	unset($ch);
}
} 
